﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using AcctrueWMS.Foundation.Data;
using AcctrueWMS.Foundation.Util;
using AcctrueWMS.Foundation.WebControls;
using NVelocity.App;
using NVelocity.Runtime;
using NVelocity;
using Commons.Collections;

using System.Web;
using AcctrueWMS.Foundation.Web;
using System.Text.RegularExpressions;
using System.IO;
namespace AcctrueWMS.Foundation.Render
{
    public class VTLModelRender : IModelRender
    {
        //在模板加载的时候，初始化Velocity
        static VTLModelRender()
        {
            //Velocity.SetProperty(NVelocity.Runtime.RuntimeConstants.VM_PERM_INLINE_LOCAL, true);
            //Velocity.SetProperty(NVelocity.Runtime.RuntimeConstants_Fields.VM_PERM_INLINE_LOCAL, true);
            ExtendedProperties props = new ExtendedProperties();
            props.Load(new FileStream(Runtime.AppPhysicalPath+ ConfigurationManager.AppSettings["nvelocity.properties"],FileMode.OpenOrCreate));
            Velocity.Init(props);
        }
        VelocityContext vltContext = new VelocityContext();

        void Init()
        {
            if (HttpContext.Current != null)
            {
                vltContext.Put("session", HttpContext.Current.Session);
                vltContext.Put("cache", HttpRuntime.Cache);
                vltContext.Put("request", HttpContext.Current.Request);
                vltContext.Put("response", HttpContext.Current.Response);
            }
            vltContext.Put("context", Context);
            vltContext.Put("render", CommonRender);
            vltContext.Put("helper",Helper);
            ///注册根路径URL
            vltContext.Put("applicationPath", Context.ApplicationPath);
            ///注册DataContext对象
            vltContext.Put("dataContext", Context);
            vltContext.Put("configer", Runtime.ConfigManager);
        }
        RenderHelper helper;
        public RenderHelper Helper
        {
            get
            {
                if (helper == null)
                    helper = new RenderHelper();
                return helper;
            }
        }

        CommonRender commonRender;
        public CommonRender CommonRender
        {
            get
            {
                if (commonRender == null)
                    commonRender = new CommonRender(Context);
                return commonRender;
            }
        }
        /// <summary>
        /// 根据模板生成页面
        /// </summary>
        /// <param name="model"></param>
        /// <param name="template"></param>
        /// <param name="tw"></param>
        public void Render(Data.DataModel model, ModelTemplate template, System.IO.TextWriter tw)
        {
            string fileFullpath = template.FilePath;
            // System.Diagnostics.Debug.Write(fileFullpath);
            if (string.IsNullOrEmpty(fileFullpath)) throw new Exception("文件未找到");

            string headFileName =HttpContext.Current.Server.MapPath(Context.ApplicationPath + "\\SysFiles\\Templates\\header.htm");
            string footFileName = HttpContext.Current.Server.MapPath(Context.ApplicationPath + "\\SysFiles\\Templates\\foot.htm");
            ///处理Section
            string html = template.InnerText;

            vltContext.Put(model.Name, model);
            //vltContext.Put("title", template.Meta.ContainsKey("title")?template.Meta["title"]:string.Empty);
            vltContext.Put("template", template);
            
            Render(ReadFileToString(headFileName),tw);            
            Render(html, tw);
            Render(ReadFileToString(footFileName),tw);
        }
      
        /// <summary>
        /// 读文件内容
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        private static string ReadFileToString(string FileName)
        {
            string readStr = string.Empty;
            using (StreamReader sr = new StreamReader(FileName))
            {
                readStr = sr.ReadToEnd();
            }
            return readStr;
        }

        
        public IDataModelContext Context
        {
            get
            {
                return Runtime.Context;
            }
        }
        /// <summary>
        /// 根据字符串生成绑定值
        /// </summary>
        /// <param name="tplStr"></param>
        /// <param name="tw"></param>
        public void Render(string tplStr, System.IO.TextWriter tw)
        {
            Init();
            try
            {
                //tplStr = CommandExprFactory.ReplaceWithEvaled(tplStr, Context);
                Velocity.Evaluate(vltContext, tw, "vlt", tplStr);
            }
            catch(Exception e)
            {
                throw e;
            }
        }
             

        /// <summary>
        /// 绑定dataModel中的值
        /// </summary>
        /// <param name="tplStr"></param>
        /// <param name="tw"></param>
        /// <param name="model"></param>
        public void Render(string tplStr, TextWriter tw, DataModel model)
        {
            Init();
            vltContext.Put("row", model);
            //tplStr = CommandExprFactory.ReplaceWithEvaled(tplStr, Context);
            Velocity.Evaluate(vltContext, tw, "vlt", tplStr);
        }

        public string Render(string tplStr)
        {
            StringWriter sw = new StringWriter();
            Render(tplStr, sw);
            return sw.ToString();
        }
    }
}
